import React, { useState } from 'react';
import { Card, Form, Input, Button, Typography, message, Row, Col } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';
import { Link, useNavigate } from 'react-router-dom';
import { login, getCurrentUser } from '../api/divide/user/sdk.gen';
import { useAuthStore } from '../store/authStore';

const { Title, Text } = Typography;

const Login: React.FC = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const navigate = useNavigate();
  const { setUser, setLoading: setAuthLoading } = useAuthStore();

  const handleLogin = async (values: { usernameOrEmail: string; password: string; rememberMe?: boolean }) => {
    setLoading(true);
    setAuthLoading(true);
    
    try {
      const response = await login({
        body: {
          usernameOrEmail: values.usernameOrEmail,
          password: values.password,
          rememberMe: values.rememberMe || false,
        },
      });

      if (response.data?.data) {
        // 获取当前用户信息
        const userResponse = await getCurrentUser();
        if (userResponse.data?.data) {
          const user = userResponse.data.data;
          
          // 存储用户信息
          setUser(user);
          
          message.success('登录成功！');
          navigate('/');
        }
      } else {
        message.error(response.data?.message || '登录失败');
      }
    } catch (error: any) {
      message.error(error.response?.data?.message || '登录失败，请检查用户名和密码');
    } finally {
      setLoading(false);
      setAuthLoading(false);
    }
  };

  return (
    <div style={{ 
      minHeight: '100vh', 
      display: 'flex', 
      alignItems: 'center', 
      justifyContent: 'center',
      background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
      padding: 20
    }}>
      <Row justify="center" style={{ width: '100%' }}>
        <Col xs={24} sm={16} md={12} lg={8} xl={6}>
          <Card style={{ 
            boxShadow: '0 8px 32px rgba(0,0,0,0.1)',
            borderRadius: 12,
            backdropFilter: 'blur(10px)',
            backgroundColor: 'rgba(255,255,255,0.95)'
          }}>
            <div style={{ textAlign: 'center', marginBottom: 24 }}>
              <Title level={2} style={{ color: '#1890ff', marginBottom: 8 }}>
                欢迎回来
              </Title>
              <Text type="secondary">登录您的Redis学习平台账号</Text>
            </div>

            <Form
              form={form}
              layout="vertical"
              onFinish={handleLogin}
              size="large"
            >
              <Form.Item
                name="usernameOrEmail"
                label="用户名/邮箱"
                rules={[
                  { required: true, message: '请输入用户名或邮箱' },
                  { min: 3, message: '用户名至少3个字符' }
                ]}
              >
                <Input 
                  prefix={<UserOutlined />} 
                  placeholder="请输入用户名或邮箱"
                  maxLength={50}
                />
              </Form.Item>

              <Form.Item
                name="password"
                label="密码"
                rules={[
                  { required: true, message: '请输入密码' },
                  { min: 6, message: '密码至少6位' }
                ]}
              >
                <Input.Password 
                  prefix={<LockOutlined />} 
                  placeholder="请输入密码"
                  maxLength={20}
                />
              </Form.Item>

              <Form.Item name="rememberMe" valuePropName="checked">
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                  <div>
                    <input type="checkbox" id="rememberMe" style={{ marginRight: 8 }} />
                    <label htmlFor="rememberMe" style={{ cursor: 'pointer' }}>记住我</label>
                  </div>
                </div>
              </Form.Item>

              <Form.Item>
                <Button 
                  type="primary" 
                  htmlType="submit" 
                  loading={loading}
                  block
                  size="large"
                  style={{ 
                    height: 48,
                    fontSize: 16,
                    fontWeight: 500
                  }}
                >
                  登录
                </Button>
              </Form.Item>

              <div style={{ textAlign: 'center', marginTop: 16 }}>
                <Text>还没有账号？ <Link to="/register">立即注册</Link></Text>
              </div>
            </Form>
          </Card>
        </Col>
      </Row>
    </div>
  );
};

export default Login;